package com.sharp.kernel.config.db;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.DefaultVFS;
import org.springframework.util.ResourceUtils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

/**
 * Title: DataSourceVfs
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2022/6/6 14:43
 */
@Slf4j
public class DataSourceVfs extends DefaultVFS {

    private static final String SEP = "/";
    private static final String XML = ".xml";
    private static final String INTERNAL_JAR_PATH = "/BOOT-INF/classes";

    @Override
    protected URL findJarForResource(URL url) throws MalformedURLException {
        url = ResourceUtils.extractJarFileURL(url);
        return (isJar(url)) ? url : null;
    }


    @Override
    protected boolean isJar(URL url) {
        return url.getPath().toLowerCase().endsWith(ResourceUtils.JAR_FILE_EXTENSION)
                || url.getPath().toLowerCase().endsWith(".war");
    }

    @Override
    protected List<String> listResources(JarInputStream jar, String path) throws IOException {
        if (!path.startsWith(SEP)) {
            path = SEP + path;
        }
        if (!path.endsWith(SEP)) {
            path = path + SEP;
        }
        List<String> resources = new ArrayList<>();
        for (JarEntry entry; (entry = jar.getNextJarEntry()) != null; ) {
            if (!entry.isDirectory()) {
                String name = entry.getName();
                if (!name.startsWith(SEP)) {
                    name = SEP + name;
                }
                if (name.startsWith(path)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Found resource: " + name);
                    }
                    resources.add(name.substring(1));
                }

                if (name.startsWith(INTERNAL_JAR_PATH + path)) {
                    if (name.endsWith(XML)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Found resource: " + name);
                        }
                    }
                    resources.add(name.substring(INTERNAL_JAR_PATH.length() + 1));
                }
            }
        }

        return resources;
    }
}
